# -*-coding:utf8-*-
import time
from selenium import webdriver
import re

URL = 'http://npd.nsfc.gov.cn/fundingProjectSearchAction.action'
TIMEOUT = 8	#如果时间超时，请增加值

def main():
    driver = webdriver.Edge()
    driver.get(URL)
    a = input('点击完成后请输入OK：')
    name = driver.find_element_by_name('fundingProject.keyword').get_attribute('value')
    p = driver.find_element_by_id("currentPageNav").text
    a = p.find('/')
    pages = int(p[a+2:-1])
    for i in range(1,pages+1):
        search = driver.find_element_by_id('currentPageGo')
        search.send_keys(str(i))
        driver.find_element_by_class_name('go pag_col').click()
        time.sleep(TIMEOUT)
        t = driver.find_element_by_id("project_result")
        text = t.text
        temp = re.sub(r' ', r'', text)
        temp = re.sub(r'([\d\u4e00-\u9fa5）])(\n)([\u4e00-\u9fa5]+：)', r'\1\t', temp)
        temp = re.sub(r'[(（万元）)(年)]', r'', temp)
        temp = re.sub(r'\t[\d\u4e00-\u9fa5]+\n', r'', temp)
        temp = re.sub(r'((\d){5,15})', r'\1\thttp://npd.nsfc.gov.cn/projectDetail.action?pid=\1', temp)
        text = re.sub(r'\n\n', r'\n', temp)
        with open(name+'.txt', 'a', encoding = 'utf-8') as fp:
            fp.write(text+'\n')

    driver.quit()
            
if __name__ == '__main__':
    main()
